﻿using BLL.Base;
using BLL.custom;
using CommandService;
using Entity;
using Entity.DbEntity;
using Microsoft.Office.Interop.Excel;
using Newtonsoft.Json;
using NPOI.OpenXmlFormats.Dml;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Configuration;

namespace BLL.Cart
{
    public partial class CartBLL
    {
        // 检查工装车编码是否有效
        public ReturnResult Check_CartCode_Valid(string json)
        {
            rsl = new ReturnResult();
            try
            {
                var code = JsonConvert.DeserializeObject<CartCodeWrapper>(json).cartCode;

                //var sql = "select * from fun_Cars_Info where cCode = '" + code + "' and isdel = 0";
                var sql = "select * from bar_SheBeiBarCode_info where barCode = '" + code + "' and status = 'Y' and barType = 'ca'";
                var dt = cmd.GetDataTable(sql);

                if (dt.Rows.Count > 0)
                {
                    rsl.Result = true;
                }
                else { rsl.Message = "工装车[" + code + "]不存在"; }

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
    }

    // 装车相关方法
    public partial class CartBLL
    {
        public ReturnResult SearchInventory(string json)
        {
            rsl = new ReturnResult();
            try
            {
                var proCode = JsonConvert.DeserializeObject<InvSearchWrapper>(json).proCodeFilter;
                var proName = JsonConvert.DeserializeObject<InvSearchWrapper>(json).proNameFilter;

                var sql = "select top 10 * from fun_Inventory_Info where isdel = 0 ";
                if (!string.IsNullOrEmpty(proCode))
                {
                    sql += "and proCode like '%" + proCode + "%' ";
                }
                if (!string.IsNullOrEmpty(proName))
                {
                    sql += "and proName like '%" + proName + "%' ";
                }

                var dt = cmd.GetDataTable(sql);
                var invList = new List<InvSelectObj>();
                foreach (DataRow row in dt.Rows)
                {
                    var pro = new InvSelectObj
                    {
                        proCode = row["proCode"].ToString(),
                        proName = row["proName"].ToString(),
                        spec = row["spec"].ToString(),
                        kezhong = row["cu_kezhong"].ToString(),
                    };
                    invList.Add(pro);
                }
                rsl.Data = invList;
                rsl.Result = true;

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        public ReturnResult QueryInventory_FreeItem(string json)
        {
            rsl = new ReturnResult();
            try
            {
                var proCode = JsonConvert.DeserializeObject<QueryFreeItemObj>(json).proCode;
                var type = JsonConvert.DeserializeObject<QueryFreeItemObj>(json).type;

                if (type == "color,brand")
                {
                    var colorSql = "select * from fun_CommonData_Info where ctype = 'procolor' and parentCode = '" + proCode + "'";
                    var colorDt = cmd.GetDataTable(colorSql);

                    var freeWraper = new FreeWraper();

                    var colorList = new List<FreeItem>();

                    // 如果该存货自由项为空，则使用通用自由项
                    if (colorDt.Rows.Count == 0)
                    {
                        var commonColorSql = "select * from fun_CommonData_Info where parentCode is null and cType = 'proColor'";
                        var commonColorDt = cmd.GetDataTable(commonColorSql);

                        foreach (DataRow row in commonColorDt.Rows)
                        {
                            var freeItem = new FreeItem { text = row["cCode"].ToString(), value = row["cName"].ToString() };
                            colorList.Add(freeItem);
                        }
                    }
                    else
                    {
                        foreach (DataRow row in colorDt.Rows)
                        {
                            var freeItem = new FreeItem { text = row["cCode"].ToString(), value = row["cName"].ToString() };
                            colorList.Add(freeItem);
                        }
                    }


                    freeWraper.alterColors = colorList;

                    var brandSql = "select * from fun_CommonData_Info where ctype = 'probrand' and parentCode = '" + proCode + "'";
                    var brandDt = cmd.GetDataTable(brandSql);

                    var brandList = new List<FreeItem>();

                    if (brandDt.Rows.Count == 0)
                    {
                        var commonBrandSql = "select * from fun_CommonData_Info where parentCode is null and cType = 'proBrand'";
                        var commonBrandDt = cmd.GetDataTable(commonBrandSql);

                        foreach (DataRow row in commonBrandDt.Rows)
                        {
                            var freeItem = new FreeItem { text = row["cCode"].ToString(), value = row["cName"].ToString() };
                            brandList.Add(freeItem);
                        }
                    }
                    else
                    {
                        foreach (DataRow row in brandDt.Rows)
                        {
                            var freeItem = new FreeItem { text = row["cCode"].ToString(), value = row["cName"].ToString() };
                            brandList.Add(freeItem);
                        }
                    }


                    freeWraper.alterBrands = brandList;

                    rsl.Data = freeWraper;
                    rsl.Result = true;
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        // 装车方法
        public ReturnResult LoadCart(string json)
        {
            rsl = new ReturnResult();
            try
            {
                var loadWrapper = JsonConvert.DeserializeObject<LoadCartWrapper>(json);

                var deviceCode = loadWrapper.cartCode;

                if (string.IsNullOrEmpty(deviceCode))
                {
                    rsl.Message = "请输入工装车设备号";
                    return rsl;
                }

                var list = loadWrapper.invCards;
                if (list == null || list.Count() == 0)
                {
                    rsl.Message = "请添加存货";
                    return rsl;
                }

                // 先查询存在的记录
                var recordSql = "select * from cart_product_info where deviceCode = '" + deviceCode + "'";
                var recordDt = cmd.GetDataTable(recordSql);

                var recordList = cmd.TableTolist<DbCartProduct>(recordDt);

                foreach (var item in recordList)
                {
                    item.id = null;
                }

                var flowCode = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                var happenTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                // 判断工装车是否在库内
                var IsCartInWarehouse = IsCartIn(deviceCode);

                // 遍历传进来的内容
                for (var i = 0; i < list.Count(); i++)
                {
                    var cart = list[i];
                    ClearNBSP(ref cart);

                    if (IsCartInWarehouse && int.Parse(cart.number) > int.Parse(cart.availableNumber))
                    {
                        rsl.Message = $@"数量超限，【{cart.proCode}|{cart.proName}|{cart.proColor}|{cart.brand}】现存量仅允许装车【{cart.availableNumber}】";
                        return rsl;
                    }

                    if (cart.number == null || cart.number == "") { rsl.Message = "请输入存货数量"; return rsl; }
                    if (int.Parse(cart.number) <= 0)
                    {
                        rsl.Message = "存货数量必须大于零";
                        return rsl;
                    }

                    // 如果之前的记录含有 存货编码，颜色，商标 匹配的存货 取出相加
                    var exist = recordList.FirstOrDefault(r =>
                    r.proCode == cart.proCode &&
                    r.proColor == cart.proColor &&
                    r.brand == cart.brand);

                    var record = new DbCartProduct();
                    // 如果记录中已经有了
                    if (exist != null)
                    {
                        exist.number = (int.Parse(exist.number) + int.Parse(cart.number)).ToString();

                        exist.flowCode = flowCode;
                        exist.createtime = happenTime;
                        exist.createuser = loadWrapper.userCode;

                    }
                    else
                    {

                        record.deviceCode = deviceCode;

                        record.flowCode = flowCode;
                        record.createtime = happenTime;
                        record.createuser = loadWrapper.userCode;

                        record.proCode = cart.proCode;
                        record.proColor = cart.proColor;
                        record.brand = cart.brand;

                        record.number = cart.number;

                        recordList.Add(record);
                    }
                }

                var operList = new List<OperateModel>();

                // 删除工装车旧记录
                var delObj = new OperateModel();
                var deleteRecord = new DbCartProduct() { deviceCode = deviceCode };
                delObj.Data = deleteRecord;
                delObj.Conditions = "deviceCode";
                delObj.Types = OperateModel.OperateType.Delete;

                operList.Add(delObj);
                //var deleteSql = "delete from cart_product_info where deviceCode = '" + deviceCode + "'";
                //var result = cmd.UpdateSql(deleteSql);

                // 添加工装车新记录
                foreach (var rec in recordList)
                {
                    var oper = new OperateModel();
                    oper.Data = rec;
                    oper.Types = OperateModel.OperateType.Add;

                    operList.Add(oper);
                }

                // 添加历史装卸车记录（转移记录）
                for (var i = 0; i < list.Count(); i++)
                {
                    var card = list[i];

                    var transferRec = new DbCartTransferRecord();

                    transferRec.flowCode = flowCode;
                    transferRec.toCart = deviceCode;
                    transferRec.createtime = happenTime;
                    transferRec.createuser = loadWrapper.userCode;
                    transferRec.number = card.number;
                    transferRec.proCode = card.proCode;
                    transferRec.proColor = card.proColor;
                    transferRec.brand = card.brand;

                    var oper = new OperateModel();
                    oper.Data = transferRec;
                    oper.Types = OperateModel.OperateType.Add;

                    operList.Add(oper);
                }

                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        // 判断工装车是否在某个库内
        public bool IsCartIn(string deviceCode, string whCode = "005")
        {
            var sql = $@"select * from fun_Cars_Info car left join bar_SheBeiBarCode_info shebei 
on shebei.sbCode = car.cCode 
where whCode = '{whCode}' and shebei.barCode = '{deviceCode}'";

            var dt = cmd.GetDataTable(sql);

            if (dt.Rows.Count > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        // 根据水洗标获取存货列表
        public ReturnResult GetInv_By_WaterWashCode(string json)
        {
            rsl = new ReturnResult();
            try
            {
                var waterCodeWrapper = JsonConvert.DeserializeObject<WrapperWashWaterQuery>(json);
                var waterCode = waterCodeWrapper.waterWashCode;
                var account = waterCodeWrapper.account;
                var deviceCode = waterCodeWrapper.deviceCode;

                var sql = "select * from fun_ShuiXiBiao_Info where outBarcode = '" + waterCode + "'";
                var dt = cmd.GetDataTable(sql);

                if (dt.Rows.Count == 0)
                {
                    rsl.Message = "水洗标【" + waterCode + "】不存在";
                    return rsl;
                }

                var invList = cmd.TableTolist<DbShuiXiBiao>(dt);

                var cardList = new List<InvCard>();
                foreach (var inv in invList)
                {
                    var card = new InvCard();

                    card.proCode = inv.proCode;
                    card.proColor = inv.proColor;
                    card.brand = inv.brand;

                    if (card.proColor == "" || card.proColor == null)
                    {
                        card.proColor = "[]";
                    }
                    if (card.brand == "" || card.brand == null)
                    {
                        card.brand = "[]";
                    }

                    card.waterWashCode = waterCode;

                    // 水洗标中没有规格，从存货表查询规格
                    var specSql = "select * from fun_Inventory_Info where proCode = '" + inv.proCode + "'";
                    var specDt = cmd.GetDataTable(specSql);

                    if (specDt.Rows.Count > 0)
                    {
                        card.spec = specDt.Rows[0]["spec"].ToString();
                        card.proName = specDt.Rows[0]["proName"].ToString();
                    }

                    // 获取根据现存量计算的建议数量
                    card.number = GetCartAvailableNumber(card.proCode, card.proColor, card.brand, account, deviceCode).ToString();
                    card.availableNumber = card.number;

                    cardList.Add(card);

                }

                rsl.Result = true;
                rsl.Data = cardList;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
    }
    // 卸车相关方法
    public partial class CartBLL
    {
        public ReturnResult Get_Invs_By_DeviceCode(string json)
        {
            rsl = new ReturnResult();
            try
            {
                var cartWrapper = JsonConvert.DeserializeObject<CartCodeWrapper>(json);
                var deviceCode = cartWrapper.cartCode;

                var sql = "select * from bar_SheBeiBarCode_info where barCode = '" + deviceCode + "' and status = 'Y' and barType = 'ca'";
                var dt = cmd.GetDataTable(sql);

                if (dt.Rows.Count == 0)
                {
                    rsl.Message = "工装车[" + deviceCode + "]不存在";
                    return rsl;
                }

                var invSql = "select * from cart_product_info where deviceCode = '" + deviceCode + "'";
                var invDt = cmd.GetDataTable(invSql);

                if (invDt.Rows.Count == 0)
                {
                    rsl.Message = "此工装车上没有存货";
                    return rsl;
                }

                var invList = cmd.TableTolist<DbCartProduct>(invDt);

                var cardList = new List<InvCard>();

                foreach (var inv in invList)
                {
                    var card = new InvCard();

                    card.proCode = inv.proCode;

                    // 水洗标中没有规格，从存货表查询规格
                    var specSql = "select * from fun_Inventory_Info where proCode = '" + inv.proCode + "'";
                    var specDt = cmd.GetDataTable(specSql);

                    if (specDt.Rows.Count > 0)
                    {
                        card.spec = specDt.Rows[0]["spec"].ToString();
                        card.proName = specDt.Rows[0]["proName"].ToString();
                    }

                    if (inv.brand == null || inv.brand == "")
                    {
                        card.brand = " ";
                    }
                    else
                    {
                        card.brand = inv.brand;
                    }

                    if (inv.proColor == null || inv.proColor == "")
                    {
                        card.proColor = " ";
                    }
                    else
                    {
                        card.proColor = inv.proColor;
                    }
                    card.number = inv.number;
                    card.maxNumber = inv.number;

                    cardList.Add(card);
                }

                rsl.Data = cardList;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        public ReturnResult UnLoadCart(string json)
        {
            rsl = new ReturnResult();
            try
            {
                var unloadWrapper = JsonConvert.DeserializeObject<LoadCartWrapper>(json);

                var deviceCode = unloadWrapper.cartCode;

                if (string.IsNullOrEmpty(deviceCode))
                {
                    rsl.Message = "请输入工装车设备号";
                    return rsl;
                }

                var list = unloadWrapper.invCards;
                if (list == null || list.Count() == 0)
                {
                    rsl.Message = "工装车上没有存货";
                    return rsl;
                }

                // 先判断用户输入的数量，是否大于工装车上的存货数量
                foreach (var inv in list)
                {
                    if (inv.number == null || inv.number == "" || int.Parse(inv.number) <= 0)
                    {
                        rsl.Message = "卸车数量必须大于0";
                        return rsl;
                    }
                    if (int.Parse(inv.number) > int.Parse(inv.maxNumber))
                    {
                        rsl.Message = "【" + inv.proName + "|" + inv.proColor + "|" + inv.brand + "】卸车数量大于工装车现存量【" + inv.maxNumber + "】";
                        return rsl;
                    }
                }

                var records = new List<DbCartTransferRecord>();

                var flowCode = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                var happenTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                var operList = new List<OperateModel>();

                foreach (var inv in list)
                {
                    // 记录
                    var rec = new DbCartTransferRecord();

                    rec.flowCode = flowCode;
                    rec.fromCart = deviceCode;
                    rec.createtime = happenTime;
                    rec.createuser = unloadWrapper.userCode;

                    rec.number = inv.number;
                    rec.proCode = inv.proCode;
                    rec.proColor = inv.proColor;
                    rec.brand = inv.brand;

                    records.Add(rec);

                    // 存货全部卸车
                    // 
                    if (inv.number == inv.maxNumber)
                    {
                        var pro = new DbCartProduct();
                        pro.deviceCode = deviceCode;
                        pro.proCode = inv.proCode;
                        pro.proColor = inv.proColor;
                        pro.brand = inv.brand;

                        var oper = new OperateModel();

                        oper.Data = pro;
                        oper.Conditions = "deviceCode,proCode,proColor,brand";
                        oper.Types = OperateModel.OperateType.Delete;

                        operList.Add(oper);
                    }
                    // 部分卸车
                    // 删除再新建工装车存货信息
                    // 以及卸车记录
                    else
                    {
                        // 车辆存货
                        var pro = new DbCartProduct();

                        pro.deviceCode = deviceCode;
                        pro.flowCode = flowCode;
                        pro.createtime = happenTime;
                        pro.createuser = unloadWrapper.userCode;

                        pro.number = (int.Parse(inv.maxNumber) - int.Parse(inv.number)).ToString();
                        pro.proCode = inv.proCode;
                        pro.proColor = inv.proColor;
                        pro.brand = inv.brand;

                        var oper = new OperateModel();

                        oper.Data = pro;
                        oper.Conditions = "deviceCode,proCode,proColor,brand";
                        oper.Types = OperateModel.OperateType.Edit;

                        operList.Add(oper);
                    }
                }



                //// 删除工装车旧记录
                //var delObj = new OperateModel();
                //var deleteRecord = new DbCartProduct() { deviceCode = deviceCode };
                //delObj.Data = deleteRecord;
                //delObj.Types = OperateModel.OperateType.Delete;

                //operList.Add(delObj);

                foreach (var rec in records)
                {
                    var oper = new OperateModel();
                    oper.Data = rec;
                    oper.Types = OperateModel.OperateType.Add;

                    operList.Add(oper);
                }

                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        public ReturnResult GetWarehouse_Position_By_DeviceCode(string json)
        {
            rsl = new ReturnResult();
            try
            {
                var wrapper = JsonConvert
                    .DeserializeObject<QueryWarehousePosition_By_DeviceCode_Wrapper>(json);

                var deviceCode = wrapper.deviceCode;

                var sbCodeSql = $@"select sbCode from bar_SheBeiBarCode_info where barCode = '{deviceCode}'; ";
                var sbCode = cmd.GetDataTable(sbCodeSql).Rows[0]["sbCode"].ToString();

                var posiSql = $@"select posCode from fun_Cars_Info where cCode = '{sbCode}'; ";
                var posiCode = cmd.GetDataTable(posiSql).Rows[0]["posCode"].ToString();

                rsl.Result = true;
                rsl.Data = posiCode;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
    }
    // 移车相关方法
    public partial class CartBLL
    {
        public ReturnResult TransferCart(string json)
        {
            rsl = new ReturnResult();
            try
            {
                // 先判断是否同一仓库，同一货位，如果是，不需要走U8接口
                var transWrapper = JsonConvert.DeserializeObject<TransferCartWrapper>(json);

                var fromCartCode = transWrapper.fromCart;
                var toCartCode = transWrapper.toCart;
                var account = transWrapper.account;
                var userCode = transWrapper.userCode;

                var IsSame = IsSamePosition(fromCartCode, toCartCode);

                if (!IsSame)
                {
                    U8Order uOrder = new U8Order();
                    rsl = uOrder.GoodsPositionChanage(json, account, userCode);

                    if (!rsl.Result)
                    {
                        return rsl;
                    }
                }

                var cards = transWrapper.invCards;
                if (cards.Count <= 0)
                {
                    rsl.Message = "未获取到转移存货信息";
                    return rsl;
                }

                // 先判断用户输入的数量，是否大于工装车上的存货数量
                foreach (var inv in cards)
                {
                    if (inv.number == null || inv.number == "" || int.Parse(inv.number) <= 0)
                    {
                        rsl.Message = "卸车数量必须大于0";
                        return rsl;
                    }
                    if (int.Parse(inv.number) > int.Parse(inv.maxNumber))
                    {
                        rsl.Message = "【" + inv.proName + "】卸车数量大于工装车现存量";
                        return rsl;
                    }
                }

                var operList = new List<OperateModel>();
                var flowCode = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                var happenTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");


                foreach (var inv in cards)
                {
                    // 处理需要卸货的工装车
                    // 如果全部卸载，删除记录
                    if (inv.number == inv.maxNumber)
                    {
                        var pro = new DbCartProduct
                        {
                            proCode = inv.proCode,
                            deviceCode = fromCartCode,
                            proColor = inv.proColor,
                            brand = inv.brand
                        };

                        var oper = new OperateModel();

                        oper.Data = pro;
                        oper.Conditions = "proCode,deviceCode,proColor,brand";
                        oper.Types = OperateModel.OperateType.Delete;

                        operList.Add(oper);
                    }
                    else
                    {
                        var pro = new DbCartProduct
                        {
                            proCode = inv.proCode,
                            deviceCode = fromCartCode,

                            createtime = happenTime,
                            flowCode = flowCode,
                            createuser = userCode,

                            number = (int.Parse(inv.maxNumber) - int.Parse(inv.number)).ToString(),
                            proColor = inv.proColor,
                            brand = inv.brand
                        };

                        var oper = new OperateModel();

                        oper.Data = pro;
                        oper.Conditions = "deviceCode,proCode,proColor,brand";
                        oper.Types = OperateModel.OperateType.Edit;

                        operList.Add(oper);
                    }

                    // 处理需要装货的工装车
                    // 检查目标工装车是否已有相同存货
                    var existNum = Check_ExistNumStr_Inventory(toCartCode, inv.proCode, inv.proColor, inv.brand);

                    // 如果目标工装车已有相同存货
                    // 修改目标工装车数量
                    if (existNum != "0")
                    {
                        var pro = new DbCartProduct
                        {
                            deviceCode = toCartCode,
                            flowCode = flowCode,
                            createtime = happenTime,
                            createuser = userCode,

                            number = (int.Parse(existNum) + int.Parse(inv.number)).ToString(),
                            proCode = inv.proCode,
                            proColor = inv.proColor,
                            brand = inv.brand,
                        };

                        var oper = new OperateModel();

                        oper.Data = pro;
                        oper.Conditions = "deviceCode,proCode,proColor,brand";
                        oper.Types = OperateModel.OperateType.Edit;

                        operList.Add(oper);
                    }
                    // 目标工装车没有相同存货
                    // 新增存货
                    else
                    {
                        var pro = new DbCartProduct
                        {
                            deviceCode = toCartCode,
                            flowCode = flowCode,
                            createtime = happenTime,
                            createuser = userCode,

                            number = inv.number,
                            proCode = inv.proCode,
                            proColor = inv.proColor,
                            brand = inv.brand,
                        };

                        var oper = new OperateModel();

                        oper.Data = pro;
                        oper.Types = OperateModel.OperateType.Add;

                        operList.Add(oper);
                    }

                    // 添加转移记录
                    var rec = new DbCartTransferRecord
                    {
                        flowCode = flowCode,
                        fromCart = fromCartCode,
                        toCart = toCartCode,
                        createtime = happenTime,
                        createuser = userCode,
                        number = inv.number,
                        proCode = inv.proCode,
                        proColor = inv.proColor,
                        brand = inv.brand,
                    };

                    var wrapper = new OperateModel();
                    wrapper.Data = rec;
                    wrapper.Types = OperateModel.OperateType.Add;

                    operList.Add(wrapper);
                }

                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                }

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        // 检查是否有相同存货，有则返回数量字符串，没有则返回"0"字符串
        string Check_ExistNumStr_Inventory(string deviceCode, string proCode, string proColor, string brand)
        {
            var sql = "select * from cart_product_info where deviceCode = '"
                + deviceCode + "' and proCode = '" + proCode + "' and proColor = '" + proColor + "' and brand = '" + brand + "'";

            var dt = cmd.GetDataTable(sql);

            if (dt.Rows.Count > 0)
            {
                var numberStr = dt.Rows[0]["number"].ToString();
                return numberStr;
            }
            else
            {
                return "0";
            }
        }

        bool IsSamePosition(string fromDeviceCode, string toDeviceCode)
        {
            var fromSbSql = $@"select sbCode from bar_SheBeiBarCode_info where barCode = '{fromDeviceCode}'";
            var fromSbDt = cmd.GetDataTable(fromSbSql);

            var fromSbCode = fromSbDt.Rows[0]["sbCode"].ToString();

            var fromPosiSql = $@"select whCode,posCode from fun_Cars_Info where cCode = '{fromSbCode}'; ";
            var fromPosiDt = cmd.GetDataTable(fromPosiSql);

            var fromWhCode = fromPosiDt.Rows[0]["whCode"].ToString();
            var fromPosCode = fromPosiDt.Rows[0]["posCode"].ToString();

            //

            var toSbSql = $@"select sbCode from bar_SheBeiBarCode_info where barCode = '{toDeviceCode}'";
            var toSbDt = cmd.GetDataTable(toSbSql);

            var toSbCode = toSbDt.Rows[0]["sbCode"].ToString();

            var toPosiSql = $@"select whCode,posCode from fun_Cars_Info where cCode = '{toSbCode}'; ";
            var toPosiDt = cmd.GetDataTable(toPosiSql);

            var toWhCode = toPosiDt.Rows[0]["whCode"].ToString();
            var toPosCode = toPosiDt.Rows[0]["posCode"].ToString();

            if (fromWhCode == toWhCode && fromPosCode == toPosCode)
            {
                return true;
            }
            return false;
        }
    }
    // 车查存货 ，存货查车相关方法
    public partial class CartBLL
    {
        public ReturnResult CartInv(string json)
        {
            rsl = new ReturnResult();
            try
            {
                var unloadWrapper = JsonConvert.DeserializeObject<LoadCartWrapper>(json);

                var deviceCode = unloadWrapper.cartCode;

//                var sql = $@"select inv.proCode,inv.proName,number,procolor,brand 
//from cart_product_info cart left join fun_Inventory_Info inv 
//on cart.proCode = inv.proCode where deviceCode = '{deviceCode}'"; 
                
                var sql = $@"select inv.proCode,inv.proName,number,procolor,brand ,w.houseName whName,com.cName posName
from cart_product_info cart 
left join fun_Inventory_Info inv on cart.proCode = inv.proCode 
left join bar_SheBeiBarCode_info b on b. barCode=cart.deviceCode
left join fun_Cars_Info c on c.cCode=b.sbCode
left join fun_WareHouse_Info w on w.houseCode=c.whCode
left join fun_CommonData_Info com on com.cCode=c.posCode and com.cType='wp'
where deviceCode ='{deviceCode}'";


                var dt = cmd.GetDataTable(sql);

                if (dt.Rows.Count == 0)
                {
                    rsl.Message = "该设备码无关联存货";
                    return rsl;
                }
                var list = cmd.TableTolist<CartInvReturnWrapper>(dt);

                rsl.Data = list;
                rsl.Result = true;
                return rsl;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        public ReturnResult InvCart(string json)
        {
            rsl = new ReturnResult();
            try
            {
                var wrapper = JsonConvert.DeserializeObject<InvCartReturnWrapper>(json);

                var proCode_filter = wrapper.proCode;
                var proName_filter = wrapper.proName;
                var proColor_filter = wrapper.proColor;
                var brand_filter = wrapper.brand;

//                var sql = $@"select top 100
//cart.barCode as deviceCode,  
//cart.sbName as cartName,
//cartInv.number,
//cartInv.proCode,
//inv.proName,
//cartInv.proColor,
//cartInv.brand
//from cart_product_info cartInv left join bar_SheBeiBarCode_info cart 
//on cartInv.deviceCode = cart.barCode left join fun_Inventory_Info inv 
//on cartInv.proCode = inv.proCode 
//where 1=1 ";

                var sql = $@"select top 100
cart.barCode as deviceCode,  
cart.sbName as cartName,
cartInv.number,
cartInv.proCode,
inv.proName,
cartInv.proColor,
cartInv.brand,
 w.houseName whName,com.cName posName
from cart_product_info cartInv 
left join bar_SheBeiBarCode_info cart on cartInv.deviceCode = cart.barCode 
left join fun_Inventory_Info inv on cartInv.proCode = inv.proCode 
left join fun_Cars_Info c on c.cCode=cart.sbCode
left join fun_WareHouse_Info w on w.houseCode=c.whCode
left join fun_CommonData_Info com on com.cCode=c.posCode and com.cType='wp'
where 1=1  ";

                var whereStr = "";
                if (!string.IsNullOrEmpty(proCode_filter))
                {
                    whereStr += $@"and cartInv.proCode like '%{proCode_filter}%' ";
                }
                if (!string.IsNullOrEmpty(proName_filter))
                {
                    whereStr += $@"and inv.proName like '%{proName_filter}%' ";
                }
                if (!string.IsNullOrEmpty(proColor_filter))
                {
                    whereStr += $@"and cartInv.proColor like '%{proColor_filter}%' ";
                }
                if (!string.IsNullOrEmpty(brand_filter))
                {
                    whereStr += $@"and cartInv.brand like '%{brand_filter}%' ";
                }

                sql += whereStr;

                var dt = cmd.GetDataTable(sql);

                if (dt.Rows.Count == 0)
                {
                    rsl.Message = "没有信息";
                    return rsl;
                }

                var returnList = cmd.TableTolist<InvCartReturnWrapper>(dt);

                rsl.Data = returnList;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
    }
    // 查询存货现存量相关方法
    public partial class CartBLL
    {
        public ReturnResult GetCurrentStock_Warehouse(string json)
        {
            rsl = new ReturnResult();
            try
            {
                var wrapper = JsonConvert.DeserializeObject<CurrentStockQueryWrapper>(json);

                var proCode = wrapper.proCode;
                var account = wrapper.account;


                var sql = $@"select wh.cWhName,cs.iQuantity,inv.cInvStd,cs.cfree1,cfree3 from V_CurrentStock cs 
left join Warehouse wh on cs.cWhCode = wh.cWhCode 
left join Inventory inv on cs.cInvCode=inv.cInvCode  
where cs.cInvCode = '{proCode}' and cs.iQuantity != 0 and cs.cWhCode != '011' order by wh.cWhName";

                var dt = cuHelper.getData(sql, account);

                if (dt.Rows.Count == 0)
                {
                    rsl.Message = "没有查询到现存量";
                    return rsl;
                }

                var list = cmd.TableTolist<CurrentStockReturnWrapper_Warehouse>(dt);

                foreach (var item in list)
                {
                    item.iQuantity = decimal.Parse(item.iQuantity).ToString("0.00");
                }

                rsl.Result = true;
                rsl.Data = list;

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        public ReturnResult GetCurrentStock_Position(string json)
        {
            rsl = new ReturnResult();
            try
            {
                var wrapper = JsonConvert.DeserializeObject<CurrentStockQueryWrapper>(json);

                var proCode = wrapper.proCode;
                var account = wrapper.account;

                var sql = $@"select wh.cWhName,pt.cPosName,ips.iQuantity,inv.cInvStd,ips.cfree1,ips.cFree3 from InvPositionSum ips
left join Warehouse wh on ips.cWhCode = wh.cWhCode
left join Position pt on ips.cPosCode = pt.cPosCode
left join Inventory inv on ips.cInvCode = inv.cInvCode
where ips.cInvCode = '{proCode}' and ips.cWhCode != '011' and ips.iQuantity != 0 order by wh.cWhName";

                var dt = cuHelper.getData(sql, account);

                if (dt.Rows.Count == 0)
                {
                    rsl.Message = "没有查询到现存量";
                    return rsl;
                }

                var list = cmd.TableTolist<CurrentStockReturnWrapper_Position>(dt);

                foreach (var item in list)
                {
                    item.iQuantity = decimal.Parse(item.iQuantity).ToString("0.00");
                }

                rsl.Data = list;
                rsl.Result = true;

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
    }

    public partial class CartBLL
    {
        public ReturnResult GetProNum(string json)
        {
            rsl = new ReturnResult();
            try
            {
                var wrapper = JsonConvert.DeserializeObject<QueryProNumWrapper>(json);

                var deviceCode = wrapper.deviceCode;
                var proCode = wrapper.proCode;
                var color = wrapper.color;
                var brand = wrapper.brand;
                var account = wrapper.account;

                rsl.Data = GetCartAvailableNumber(proCode, color, brand, account, deviceCode);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        // 获取可装车数量
        // 005是新半成品库，以后如果有其它库房再改
        public int GetCartAvailableNumber(string proCode, string color, string brand, string account, string deviceCode)
        {
            // 查询 仓库编码和货位编码
            var whCode_posCode_query_sql =
                $@"select whCode,posCode from fun_Cars_Info 
where ccode in (select sbCode 
from bar_SheBeiBarCode_info where barCode = '{deviceCode}')";

            var whCode_posCode_query_dt = cmd.GetDataTable(whCode_posCode_query_sql);

            if (whCode_posCode_query_dt.Rows.Count == 0)
            {
                return 0;
            }

            var whCode = whCode_posCode_query_dt.Rows[0]["whCode"].ToString();
            var posCode = whCode_posCode_query_dt.Rows[0]["posCode"].ToString();

            //查与该工装车相同的货位上
            //所有的 工装车存货表里储存的数量
            var proNumberSql = $@"select sum(cast(number as int)) proNum from cart_product_info where deviceCode in 
(select barCode from bar_SheBeiBarCode_info where sbCode in 
(select cCode from fun_Cars_Info where whCode = '{whCode}' and posCode = '{posCode}' )) 
and proCode = '{proCode}' and proColor = '{color}' and brand = '{brand}'; ";

            var proNumdt = cmd.GetDataTable(proNumberSql);

            var proNum = 0;

            try
            {
                proNum = int.Parse(proNumdt.Rows[0]["proNum"].ToString());
            }
            catch (Exception)
            {

            }

            // 货位该存货数量

            if (color == "[]")
            {
                color = "";
            }

            if (brand == "[]")
            {
                brand = "";
            }

            //            var whNumSql = $@"select sum(iQuantity) as whNum from V_CurrentStock 
            //where cInvCode = '{proCode}' and iQuantity != 0 and cWhCode = '{whCode}' and cfree1 = '{color}' and cfree3 = '{brand}' ";
            //            var whNumDt = cuHelper.getData(whNumSql, account);

            //            var whNum = 0;

            //            try
            //            {
            //                whNum = int.Parse(whNumDt.Rows[0]["whNum"].ToString().TrimEnd('0').TrimEnd('.'));
            //            }
            //            catch (Exception)
            //            {
            //            }

            var posNumSql = $@"select sum(iQuantity) as posNum from InvPositionSum WHERE cInvCode = '{proCode}' and cfree1 = '{color}' and cfree3 = '{brand}' 
and cWhCode = '{whCode}' and cPosCode = '{posCode}' and cWhCode != '011' and iQuantity != 0 ";
            var posNumDt = cuHelper.getData(posNumSql, account);

            var posNum = 0;

            try
            {
                posNum = int.Parse(posNumDt.Rows[0]["posNum"].ToString().TrimEnd('0').TrimEnd('.'));
            }
            catch (Exception)
            {
            }

            return posNum - proNum;
        }
    }

    public partial class CartBLL
    {
        public ReturnResult EmptyInOut(string json)
        {
            rsl = new ReturnResult();
            try
            {
                var wrapper = JsonConvert.DeserializeObject<QueryEmptyInOutWrapper>(json);

                var deviceCode = wrapper.deviceCode;
                var posCode = wrapper.posCode;



                // 检测是否空车
                var IsEmpty = IsCartEmpty(deviceCode);
                if (!IsEmpty)
                {
                    rsl.Message = "只允许空车操作";
                    return rsl;
                }

                var shebei_sql = $@"select sbCode from bar_SheBeiBarCode_info where barCode = '{deviceCode}' and barType = 'ca'; ";
                var shebei_dt = cmd.GetDataTable(shebei_sql);

                if (shebei_dt.Rows.Count == 0)
                {
                    rsl.Message = "设备号不存在";
                    return rsl;
                }

                var sbCode = shebei_dt.Rows[0]["sbCode"].ToString();

                var whCode_sql = $@"select whCode from fun_Cars_Info where cCode = '{sbCode}'";
                var whCode_dt = cmd.GetDataTable(whCode_sql);

                var whCode = whCode_dt.Rows[0]["whCode"].ToString();

                // 如果车辆未入库
                if (string.IsNullOrEmpty(whCode))
                {
                    if (string.IsNullOrEmpty(posCode))
                    {
                        rsl.Message = "请选择新半成品货位";
                        return rsl;
                    }

                    var updateSql = $@"update fun_Cars_Info set whCode = '005', posCode = '{posCode}' where cCode = '{sbCode}'";
                    var updateResult = cmd.UpdateSql(updateSql);

                    if (updateResult.Result)
                    {
                        rsl.Message = "空车已入货位";
                        rsl.Result = true;
                        return rsl;
                    }
                    else
                    {
                        return updateResult;
                    }
                }
                // 如果车辆已入库
                else
                {
                    var updateSql = $@"update fun_Cars_Info set whCode = NULL, posCode = NULL  where cCode = '{sbCode}'";
                    var updateResult = cmd.UpdateSql(updateSql);

                    if (updateResult.Result)
                    {
                        rsl.Message = "空车已出库";
                        rsl.Result = true;
                        return rsl;
                    }
                    else
                    {
                        return updateResult;
                    }
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        public ReturnResult WhereIsCart(string json)
        {
            rsl = new ReturnResult();
            try
            {
                var wrapper = JsonConvert.DeserializeObject<QueryEmptyInOutWrapper>(json);

                var deviceCode = wrapper.deviceCode;

                var sb_sql = $@"select sbCode from bar_SheBeiBarCode_info where barCode = '{deviceCode}';";
                var sb_dt = cmd.GetDataTable(sb_sql);

                if (sb_dt.Rows.Count == 0)
                {
                    rsl.Message = "工装车不存在";
                    return rsl;
                }

                if (IsCartIn_Or_Out(sb_dt.Rows[0]["sbCode"].ToString()))
                {
                    rsl.Data = "库内";
                    rsl.Result = true;
                    return rsl;
                }
                else
                {
                    rsl.Data = "库外";
                    rsl.Result = true;
                    return rsl;
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        public bool IsCartEmpty(string deviceCode)
        {
            var sql = $@"select * from cart_product_info where devicecode = '{deviceCode}';";
            var dt = cmd.GetDataTable(sql);
            if (dt.Rows.Count != 0)
            {
                return false;
            }
            return true;
        }
        // 工装车是否在库
        // true 在库
        // false 不在库
        public bool IsCartIn_Or_Out(string sbCode)
        {
            var sql = $@"select whCode from fun_Cars_Info where cCode = '{sbCode}'; ";
            var dt = cmd.GetDataTable(sql);
            if (string.IsNullOrEmpty(dt.Rows[0]["whCode"].ToString()))
            {
                return false;
            }
            else
            {
                return true;
            }

        }
    }

    public partial class CartBLL
    {
        public ReturnResult GetPositionSelectors(string json)
        {
            rsl = new ReturnResult();
            try
            {
                var wrapper = JsonConvert.DeserializeObject<QueryPositionsWrapper>(json);

                var sql = "select cPosCode,cPosName from [Position] WHERE cWhCode = '005'";
                var dt = cuHelper.getData(sql, wrapper.account);

                var list = new List<FreeItem>();

                foreach (DataRow row in dt.Rows)
                {
                    list.Add(new FreeItem
                    {
                        text = row["cPosName"].ToString(),
                        value = row["cPosCode"].ToString()
                    });
                }

                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
    }

    public partial class CartBLL
    {
        ReturnResult rsl;
        Commands cmd;
        LoginInfo userLogin;
        CuDbHelper cuHelper;

        public CartBLL()
        {
            cmd = new Commands();
            userLogin = new LoginInfo();
            cuHelper = new CuDbHelper();
        }
    }

    public partial class CartBLL
    {
        // 清理空白占位符 
        void ClearNBSP(ref InvCard invCard)
        {
            if (invCard.proColor == " ")
            {
                invCard.proColor = "[]";
            }

            if (invCard.brand == " ")
            {
                invCard.brand = "[]";
            }
        }
    }

    // 以下为容器类

    class CartCodeWrapper
    {
        public string cartCode { get; set; }
    }

    class InvSearchWrapper
    {
        public string proCodeFilter { get; set; }
        public string proNameFilter { get; set; }
    }
    class InvSelectObj
    {
        public string proCode { get; set; }
        public string proName { get; set; }
        public string spec { get; set; }
        public string kezhong { get; set; }
    }
    class QueryFreeItemObj
    {
        public string proCode { get; set; }
        public string type { get; set; }
    }

    class FreeItem
    {
        public string text { get; set; }
        public string value { get; set; }
    }
    class FreeWraper
    {
        public List<FreeItem> alterColors { get; set; }
        public List<FreeItem> alterBrands { get; set; }
    }

    class LoadCartWrapper
    {
        public string cartCode { get; set; }
        public string userCode { get; set; }
        public string account { get; set; }
        public List<InvCard> invCards { get; set; }
    }

    class TransferCartWrapper
    {
        public string account { get; set; }
        public string fromCart { get; set; }
        public string toCart { get; set; }
        public string userCode { get; set; }
        public List<InvCard> invCards { get; set; }
    }

    class InvCard
    {
        public bool selected { get; set; }

        public string waterWashCode { get; set; }
        public string index { get; set; }
        public string proCode { get; set; }
        public string proName { get; set; }
        public string spec { get; set; }

        string _proColor { get; set; }
        public string proColor
        {
            get
            {
                if (_proColor == null || _proColor == "" || _proColor == " " || _proColor == " ")
                {
                    return "[]";
                }
                else
                {
                    return _proColor;
                }
            }

            set
            {
                _proColor = value;
            }
        }

        string _brand { get; set; }
        public string brand
        {
            get
            {
                if (_brand == null || _brand == "" || _brand == " " || _brand == " ")
                {
                    return "[]";
                }
                else
                {
                    return _brand;
                }
            }

            set
            {
                _brand = value;
            }
        }
        public string number { get; set; }

        // 工装车上的数量，卸车用
        public string maxNumber { get; set; }

        // 现存量允许的最大装车数量，装车用
        public string availableNumber { get; set; }
    }

    class WrapperWashWaterQuery
    {
        public string deviceCode { get; set; }
        public string waterWashCode { get; set; }
        public string account { get; set; }
    }

    class CartInvReturnWrapper
    {
        public string proCode { get; set; }
        public string proName { get; set; }
        public string number { get; set; }
        public string proColor { get; set; }
        public string brand { get; set; }
        public string whName { get; set; }
        public string posName { get; set; }
    }

    class InvCartReturnWrapper
    {
        public string deviceCode { get; set; }
        public string cartName { get; set; }
        public string number { get; set; }
        public string proCode { get; set; }
        public string proName { get; set; }
        public string proColor { get; set; }
        public string brand { get; set; }
    }
    class CurrentStockQueryWrapper
    {
        public string proCode { get; set; }
        public string account { get; set; }
    }
    class CurrentStockReturnWrapper_Warehouse
    {
        public string cWhName { get; set; }
        public string iQuantity { get; set; }
        public string cInvStd { get; set; }
        public string cfree1 { get; set; }
        public string cfree3 { get; set; }
    }

    class CurrentStockReturnWrapper_Position
    {
        public string cWhName { get; set; }
        public string cPosName { get; set; }
        public string iQuantity { get; set; }
        public string cInvStd { get; set; }
        public string cfree1 { get; set; }
        public string cfree3 { get; set; }
    }

    class QueryProNumWrapper
    {
        public string deviceCode { get; set; }
        public string proCode { get; set; }
        public string color { get; set; }
        public string brand { get; set; }
        public string account { get; set; }
    }
    class QueryEmptyInOutWrapper
    {
        public string deviceCode { get; set; }
        public string posCode { get; set; }
    }

    class QueryPositionsWrapper
    {
        public string account { get; set; }
    }

    class QueryWarehousePosition_By_DeviceCode_Wrapper
    {
        public string deviceCode { get; set; }
    }
}
